<template>
  <div class="app-container">
    <!-- 查询操作 -->
    <div class="filter-container">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="formInline.cardNo" :placeholder='$t("请输入礼物卡编号")' clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="formInline.userName" :placeholder='$t("请输入会员账号")' clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formInline.bindStatus" :placeholder='$t("请输入绑定状态")' clearable>
            <el-option :label='$t("未绑定")' value="0"></el-option>
            <el-option :label='$t("已绑定")' value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formInline.status" :placeholder='$t("请输入使用状态")' clearable>
            <el-option :label='$t("未使用")' value="0"></el-option>
            <el-option :label='$t("使用中")' value="1"></el-option>
            <el-option :label='$t("已停用")' value="2"></el-option>
          </el-select>
        </el-form-item>
        <!--          <el-form-item :label='$t("礼物卡分类")'>
                    <el-select
                        v-model="formInline.classificationId"
                        clearable
                        class="filter-item"
                        :placeholder="$t('请选择礼物卡分类')"
                    >
                      <el-option
                          v-for="item in cardList"
                          :key="item.id"
                          :value="item.id"
                          :label="item.classificationName"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item :label='$t("请选择门店")'>
                    <el-select
                        v-model="formInline.shopId"
                        clearable
                        class="filter-item"
                        :placeholder="$t('请选择门店')"
                    >
                      <el-option
                          v-for="item in shops"
                          :key="item.id"
                          :value="item.id"
                          :label="item.name"
                      ></el-option>
                    </el-select>
                  </el-form-item>-->

        <el-form-item>
          <el-date-picker
            v-model="formInline.dateRange"
            type="datetimerange"
            start-placeholder="请选择开始时间"
            end-placeholder="请选择结束时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
            :picker-options="datePickerShortcuts"
          >
          </el-date-picker>
        </el-form-item>


        <el-button  class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter" v-permission="['GET /admin/p/card_entity_statistic_list']">{{$t("查询")}}</el-button>
        <!--            <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilters">{{$t("导出")}}</el-button>-->
        <el-upload v-if="this.uploadStatus == 0 "
                   class="upload-demo"
                   ref="upload"
                   :action="easyExcelPath"
                   :on-preview="handlePreview"
                   :on-remove="handleRemove"
                   :data="{cardId: this.formInline.giftCardId}"
                   :drag="true"
                   :on-success="handleSuccess"
                   accept=".xlsx"
                   :file-list="fileList"
                   :auto-upload="false" v-permission="['GET /admin/p/card_entity_statistic_upload']">
          <el-button slot="trigger" type="primary" v-permission="['GET /admin/p/card_entity_statistic_upload']">{{$t("选取文件")}}</el-button>
          <el-button style="margin-left: 10px;" type="success" @click="submitUpload" v-permission="['GET /admin/p/card_entity_statistic_upload']">{{$t("上传到服务器")}}</el-button>
          <!--        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>-->
        </el-upload>      <!-- 查询结果 -->
      </el-form>
    </div>
    <el-card class="box-card">
      <h3>{{$t("概况")}}</h3>
      <div class="table-layout">
        <el-row>
          <el-col :span="2" class="table-cell-title">{{$t("礼物卡")}}</el-col>
          <el-col :span="2" class="table-cell-title">{{$t("礼物卡总数量")}}</el-col>
          <el-col :span="2" class="table-cell-title">{{$t("绑卡数量")}}</el-col>
          <el-col :span="2" class="table-cell-title">{{$t("未使用/张")}}</el-col>
          <el-col :span="2" class="table-cell-title">{{$t("使用中/张")}}</el-col>
          <el-col :span="2" class="table-cell-title">{{$t("已停用/张")}}</el-col>
          <el-col :span="3" class="table-cell-title">{{$t("总充值金额")}}</el-col>
          <el-col :span="3" class="table-cell-title">{{$t("总余额金额")}}</el-col>
          <el-col :span="3" class="table-cell-title">{{$t("总消费金额")}}</el-col>
        </el-row>
        <el-row>
          <el-col :span="2" class="table-cell">{{ gift.name }}</el-col>
          <el-col :span="2" class="table-cell">{{ gift.numbers==0?$t("无限量"): gift.numbers}}</el-col>
          <el-col :span="2" class="table-cell">{{ gift.bindNum}}</el-col>
          <el-col :span="2" class="table-cell">{{ gift.noUseNum }}</el-col>
          <el-col :span="2" class="table-cell">{{ gift.inUseNum }}</el-col>
          <el-col :span="2" class="table-cell">{{ gift.stopNum }}</el-col>
          <el-col :span="3" class="table-cell">{{ NumberUtils.formatCurrency(gift.totalRechargeAmount) }}</el-col>
          <el-col :span="3" class="table-cell">{{ NumberUtils.formatCurrency(gift.totalAmount) }}</el-col>
          <el-col :span="3" class="table-cell">{{ NumberUtils.formatCurrency(gift.useAmount) }}</el-col>
        </el-row>
      </div>
    </el-card>

    <el-card class="box-card">
      <h3>{{$t("详情")}}</h3>

      <div style="margin-bottom: 10px;">
        <el-button type="primary" size="mini" @click="batchToggleStatus(1)">批量启用</el-button>
        <el-button type="danger" size="mini" @click="batchToggleStatus(2)">批量停用</el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="userList"
        :element-loading-text="$t('Searching')"
        border
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
            type="index"
            align="center"
            :label="$t('序号')"
            width="50">
        </el-table-column>
        <el-table-column align="center" :label='$t("礼物卡编号")' prop="cardNumber">
        </el-table-column>
        <el-table-column align="center" :label='$t("会员账号")' prop="userName">
        <template slot-scope="scope">
          <!-- 0--未使用。1--使用中.2--已停用 -->
          <span style="color: #3399ff">{{ scope.row.userName ? scope.row.userName :  '未绑定' }}</span>
        </template>
        </el-table-column>
        <el-table-column align="center" :label='$t("用户姓名")' prop="nikeName">
          <template slot-scope="scope">
            <!-- 0--未使用。1--使用中.2--已停用 -->
            {{ scope.row.nikeName ? scope.row.nikeName :  '未绑定' }}
          </template>
        </el-table-column>

        <el-table-column align="center" :label='$t("手机号码")' prop="mobile"/>
        <el-table-column align="center" :label='$t("绑定状态")' prop="isBand">
          <template slot-scope="scope">
            <!-- 0--未使用。1--使用中.2--已停用 -->
            <span style="color: #3399ff">{{ scope.row.entityCardCode ? '已绑定' :  '未绑定' }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" :label="$t('状态')" prop="status">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : scope.row.status === 0 ? 'info' : 'danger'">
              {{
                scope.row.status === 0
                  ? "未使用"
                  : scope.row.status === 1
                    ? "使用中"
                    : "已停用"
              }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          :label="$t('总充值金额')"
          prop="totalRechargeAmount"
          :formatter="NumberUtils.formatCurrencyInTable"
        />
        <el-table-column align="center" :label='$t("总余额")' prop="amount">
          <template slot-scope="scope">
            <!-- 0--未使用。1--使用中.2--已停用 -->
            <span>{{ NumberUtils.formatCurrency(scope.row.amount) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          :label="$t('总消费金额')"
          :formatter="NumberUtils.formatCurrencyInTable"
          prop="useAmount"
        />
        <el-table-column
          align="center"
          :label="$t('绑卡时间')"
          prop="addTime"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.bindTime"> {{formatDateToYYYYMMDD(scope.row.bindTime)}}</span>
          </template>
        </el-table-column>
        <el-table-column
            align="center"
            :label="$t('添加时间')"
            prop="updateTime"
        >
          <template slot-scope="scope">
           {{formatDateToYYYYMMDD(scope.row.updateTime)}}
          </template>
        </el-table-column>
        <el-table-column align="center" :label='$t("操作")' width="300">
          <template slot-scope="scope">
            <el-button  size="mini" type="primary" @click="handleBind(scope.row)" v-permission="['GET /admin/p/card_entity_statistic_list']">{{$t("查看明细")}}</el-button>
            <el-button  size="mini" type="danger" icon="el-icon-delete" @click="handleDeleted(scope.row)" v-permission="['GET /admin/p/card_entity_statistic_deleted']"></el-button>
            <!-- 启用/停用按钮 -->
            <el-button
              v-if="scope.row.status === 2"
              type="success"
              size="mini"
              @click="toggleSingleUserStatus(scope.row.id, 1)"
            >
              启用
            </el-button>
            <el-button
              v-else
              type="danger"
              size="mini"
              @click="toggleSingleUserStatus(scope.row.id, 2)"
            >
              停用
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="userTotal>0" :total="userTotal" :page.sync="formInline.page" :limit.sync="formInline.limit"
                  @pagination="getUserList"/>
    </el-card>
  </div>
</template>

<script>
import { typeUserStatistic,entityRemove,toggleUserStatus } from '@/api/gift'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { easyExcelPath } from '../../api/storage'
import { singleEntityTypeStatisticTotal } from '../../api/gift'
import { cardClassificationList } from "@/api/cardClassification";
import { allForPerm } from "@/api/shop";
import NumberUtils from "../../utils/numberUtils";
import {formatDateToYYYYMMDD,datePickerShortcuts} from "../../utils/date";
export default {
  name: 'cardStatisticsdetail',
  components: { Pagination },
  data() {
    const typeMap = {
      '1': this.$t('全场通用'),
      '2': this.$t('指定类目')
    }
    return {
      NumberUtils,
      multipleSelection: [],
      //卡类型
      cardList:[],
      shops: [], //所有门店信息
      formInline: {
        giftCardId: undefined,
        page: 1,
        limit: 20,
        dateRange: [],
      },

      fileList: [],
      easyExcelPath,
      typeMap,
      gift: {},
      userList: [],
      userTotal: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        giftCardId: undefined,
        userName: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      bindDialogVisible: false,
      bindForm: {
        id: undefined,
        entityCardCode: undefined
      },
      uploadStatus: undefined,
      datePickerShortcuts,
    }
  },
  created() {
    this.formInline.giftCardId = this.$route.query.id
    this.getUserList();
    this.getCardClassification();
    allForPerm().then((response) => {
      this.shops = response.data.data.list;
    });
  },
  methods: {
    formatDateToYYYYMMDD,
    //获取卡类型列表
    getCardClassification() {
      var formInline = {
        classificationName: undefined,
        classificationStatus: undefined,
        page: 1,
        limit: 1000,
        sort: "add_time",
        order: "desc",
      };
      cardClassificationList(formInline)
          .then((response) => {
            this.cardList = response.data.data.list;
          })
          .catch(() => {
            this.cardList = [];
          });
    },
    getUserList() {
      singleEntityTypeStatisticTotal(this.formInline).then(response => {
        this.gift = response.data.data
      })

      typeUserStatistic(this.formInline).then(response => {
        this.userList = response.data.data.list
        this.userTotal = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.userList = []
        this.userTotal = 0
        this.listLoading = false
      })
    },
    handleDeleted(row){
      if(row.status==1){
        this.$notify({
          title: '警告',
          message: '使用中不可删除！',
          type: 'warning'
        });
        return;
      }
      this.$confirm(this.$t('此操作将永久删除, 是否继续?'), this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        entityRemove(row.id).then(res=>{
          this.integralDialogVisible = false
          this.handlePointDialogVisible = false
          this.getUserList()
          this.$notify.success({
            title: this.$t('Success!'),
            message: this.$t('Success!')
          })
        }).catch(response => {
          this.$notify.error({
            title: this.$t('Failed'),
            message: this.$t(response.data.errmsg)
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('已取消删除')
        });
      });
    },
    handleFilter() {
      this.getUserList()
    },

    submitUpload() {
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {
    },

    handleSuccess(data) {
      const newDatas = []
      const h = this.$createElement
      for (const i in data.data.list) {
        newDatas.push(h('p', null, data.data.list[i]))
      }

      this.fileList = []

      this.getUserList()
    },
    handlePreview(file) {
    },
    handleBind(row) {
      this.$router.push({ path: '/promotion/cardStatistics/cardStatisticsdetail/details', query: { allData: row.id ,status:1} })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.id)
    },
    batchToggleStatus(status) {
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请先选择要操作的记录");
        return;
      }
      const actionText = status === 1 ? '启用' : '停用';
      this.$confirm(`确定要${actionText}选中的用户吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        toggleUserStatus({ ids: this.multipleSelection, status }).then(() => {
          this.$message.success("操作成功");
          this.getUserList();
        }).catch(() => {
          this.$message.error("操作失败");
        });
      }).catch(() => {
        this.$message.info("已取消操作");
      });
    },
    // 单个用户启用/停用
    toggleSingleUserStatus(id, status) {
      const actionText = status === 1 ? '启用' : '停用';
      this.$confirm(`确定要${actionText}该用户吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        toggleUserStatus({ ids: [id], status }).then(() => {
          this.$message.success("操作成功");
          this.getUserList();
        }).catch(() => {
          this.$message.error("操作失败");
        });
      }).catch(() => {
        this.$message.info("已取消操作");
      });
    }
  }
}
</script>

<style scoped>
.filter-container {
  margin-top: 20px;
}

.table-layout {
  margin-top: 20px;
  border-left: 1px solid #DCDFE6;
  border-top: 1px solid #DCDFE6;
}

.table-cell {
  height: 60px;
  line-height: 40px;
  border-right: 1px solid #DCDFE6;
  border-bottom: 1px solid #DCDFE6;
  padding: 10px;
  font-size: 14px;
  color: #606266;
  text-align: center;
  overflow: hidden;
}

.table-cell-title {
  border-right: 1px solid #DCDFE6;
  border-bottom: 1px solid #DCDFE6;
  padding: 10px;
  background: #F2F6FC;
  text-align: center;
  font-size: 14px;
  color: #303133;
}
</style>


